let _Vue = null

export default class VueRouter {
    constructor (options) {
        this.options = options
        this.routeMap = {}
        this.data = _Vue.observable({
            current: '/'
        })
        this.push = null
    }

    static install (Vue) {
        // 判读当前插件是否被安装
        if (VueRouter.install.installed) return

        VueRouter.install.installed = true

        _Vue = Vue

        _Vue.mixin({
            beforeCreate() {
                if (!this.$options.router) return 
                _Vue.prototype.$router = this.$options.router
                this.$options.router.init()
            }
        })
    }

    // 解析路由
    createRouteMap () {
        this.options.routes.forEach(route => {
            this.routeMap[route.path] = route.component
        })
    }

    // 初始化调用
    init () {
        this.createRouteMap()
        this.initComponents()
        this.initEvent()
        this.push = this.initPush()
    }

    // 自定义push 方法 , 暂时只实现路径push
    initPush () {
        return (url) => {
            location.hash = url
        }
    }

    // 定义组件
    initComponents () {
        const _that = this
        _Vue.component('router-view', {
            render (h) {
                const router = _that.routeMap[_that.data.current]
                return h(router)
            }
        })
    }

    // 注册事件
    initEvent () {
        window.addEventListener('hashchange',() =>{
            const url = window.location.hash.substr(1)
            this.data.current = url || '/'
            // 加载对应的 组件
            console.log(url);
         })
    }
}